package com.smalls.newvideotwo.module.welcome;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.smalls.newvideotwo.BuildConfig;
import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.R;
import com.smalls.newvideotwo.auth.AAAActivateResult;
import com.smalls.newvideotwo.auth.AAAActivateTask;
import com.smalls.newvideotwo.auth.AAARegisterResult;
import com.smalls.newvideotwo.auth.AAARegisterTask;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.utils.Constant;
import com.smalls.newvideotwo.utils.MeasureUtil;
import com.smalls.newvideotwo.utils.Utils;
import com.smalls.newvideotwo.view.ConfirmDialog;
import com.smalls.newvideotwo.view.NetworkDialog;
import com.uking.helper.VKNetBossUtils;

import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WelcomeActivity extends Activity {
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + WelcomeActivity.class.getSimpleName():WelcomeActivity.class.getSimpleName();
    private String CODE = null;
    View contentView;
    private LinearLayout mLoadingLayout;
    private NetworkDialog mDlg=null;
    private final static int FAIL_TRY_COUNT=3;
    private int mCountFail=0;
    private String mUidString = "";
    private String mInputString = null;
    private List<String> m3AIPList = new ArrayList<>();
    private int m3AIPPosition = 0;
    private String aaa = BuildConfig.DOMAIN_AAA_2;
	private boolean isDel =false;
    private AAARegisterTask aaaRegisterTask=null;
    private AAAActivateTask aaaActivateTask=null;
    private Handler mHandler = new Handler();

    private String get3AIP() {
        if(m3AIPList.size()>0) {
            if(m3AIPPosition<m3AIPList.size()) {
                return m3AIPList.get(m3AIPPosition++);
            } else {
                return null;
            }
        } else {
            if(m3AIPPosition==0) {
                m3AIPPosition++;
                return BuildConfig.DOMAIN_AAA_1;
            } else {
                return null;
            }
        }
    }

    private void getAllByName(String domainname) {
        try {
            LogUtil.d(TAG,"使用InetAddress类的方法获取网站" + domainname + "的IP地址...");

            LogUtil.d(TAG,"总共ip个数：" + InetAddress.getAllByName(domainname).length);//获取接续出来的ip的个数
            InetAddress[] inetadd = InetAddress.getAllByName(domainname);
            //遍历所有的ip并输出
            for (int i = 0; i < inetadd.length; i++) {
                LogUtil.d(TAG,"第" + (i + 1) + "个ip：" + inetadd[i].getHostAddress());
                if(inetadd[i].getHostAddress()!=null) {
                    m3AIPList.add(inetadd[i].getHostAddress());
                }
            }

        } catch(UnknownHostException e) {
            LogUtil.d(TAG,"获取"+domainname+"的IP地址失败！没有对应的IP！");
        }

    }


    private Runnable mRunnable = new Runnable() {
        public void run() {
            // 弹出PopupWindow的具体代码
            //NewDTVApp.getApp().editor.putString("uid","").commit();
            getAllByName(BuildConfig.DOMAIN_AAA_0);
            aaa = get3AIP();
            LogUtil.d(TAG,"m3AIPPosition="+m3AIPPosition);
            ///NewDTVApp.getApp().sharedPre.edit().putString("uid","").commit();
            mUidString = VKNetBossUtils.decrypt(NewDTVApp.getApp().sharedPre.getString("uid",""), Constant.KEY);
            LogUtil.d(TAG,"mUidString="+mUidString);

            if(mUidString.equals("")) {////没有激活，需要激活
                LogUtil.d(TAG,"no uid,check had activated?");
                mCountFail = 0;
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        showPopupWindow(WelcomeActivity.this,contentView);
                    }
                },500);

            } else {
                mCountFail = 0;
                registerAAA(aaa,mRegisterResultListener,mUidString);
            }
        }
    };

    public void registerAAA(String aaa, AAARegisterTask.OnResultListener onResultListener, String uid) {
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(aaaRegisterTask !=null && aaaRegisterTask.getStatus() == AsyncTask.Status.RUNNING){
            aaaRegisterTask.cancel(true);
            aaaRegisterTask=null;
        }
        aaaRegisterTask = new AAARegisterTask();
        aaaRegisterTask.setOnResultListener(onResultListener);
        aaaRegisterTask.set3A(aaa);
        aaaRegisterTask.execute(uid);
    }

    public void activateAuth(String aaa, AAAActivateTask.OnResultListener onResultListener, String code) {
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(aaaActivateTask !=null && aaaActivateTask.getStatus() == AsyncTask.Status.RUNNING){
            aaaActivateTask.cancel(true);
            aaaActivateTask=null;
        }
        aaaActivateTask = new AAAActivateTask();
        aaaActivateTask.setOnResultListener(onResultListener);
        aaaActivateTask.set3A(aaa);
        aaaActivateTask.execute(code);
    }

    private void hideBufferLoad() {
        if (mLoadingLayout != null
                && mLoadingLayout.getVisibility() == View.VISIBLE) {
            mLoadingLayout.clearAnimation();
            mLoadingLayout.setVisibility(View.GONE);
            LogUtil.d(TAG, "hide load");
        }
    }

    private void showBufferLoad() {
        if (mLoadingLayout != null
                && mLoadingLayout.getVisibility() != View.VISIBLE) {
            mLoadingLayout.setVisibility(View.VISIBLE);
            LogUtil.d(TAG, "show load");
        }
    }

    public void enableShowSoftInput(EditText editText) {
        if (Build.VERSION.SDK_INT <= 10) {
            editText.setInputType(0);
            return;
        }
        Class<EditText> cls = EditText.class;
        try {
            Method method = cls.getMethod("setShowSoftInputOnFocus", new Class[]{Boolean.TYPE});
            method.setAccessible(true);
            method.invoke(editText, new Object[]{Boolean.valueOf(true)});
        } catch (Exception e) {
        }
        try {
            Method method = cls.getMethod("setSoftInputShownOnFocus", new Class[]{Boolean.TYPE});
            method.setAccessible(true);
            method.invoke(editText, new Object[]{Boolean.valueOf(true)});
        } catch (Exception e2) {
        }
    }

    public void showPopupWindow(Context context,View parent){
        LayoutInflater inflater = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View vPopupWindow=inflater.inflate(R.layout.input_dialog, null, false);
        final EditText mEditText = (EditText)vPopupWindow.findViewById(R.id.input_dialog_input);
        LinearLayout.LayoutParams iconPa = (LinearLayout.LayoutParams) mEditText
                .getLayoutParams();
        iconPa.width = (int) MeasureUtil.getWidthSize(600);
        iconPa.height = (int) MeasureUtil.getHeightSize(60);
        mEditText.setLayoutParams(iconPa);
        enableShowSoftInput(mEditText);

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            public void run() {
                InputMethodManager inputManager = (InputMethodManager) mEditText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(mEditText, 0);
            }

        }, 500);
        TextView textViewOK = (TextView)vPopupWindow.findViewById(R.id.input_dialog_ok);
        LinearLayout.LayoutParams textViewOKPa = (LinearLayout.LayoutParams) textViewOK
                .getLayoutParams();
        textViewOKPa.width = (int) MeasureUtil.getWidthSize(264);
        textViewOKPa.height = (int) MeasureUtil.getHeightSize(74);
        textViewOK.setLayoutParams(textViewOKPa);
        TextView textViewCancel = (TextView)vPopupWindow.findViewById(R.id.input_dialog_cancel);
        LinearLayout.LayoutParams textViewCancelPa = (LinearLayout.LayoutParams) textViewCancel
                .getLayoutParams();
        textViewCancelPa.width = (int) MeasureUtil.getWidthSize(264);
        textViewCancelPa.height = (int) MeasureUtil.getHeightSize(74);
        textViewCancel.setLayoutParams(textViewOKPa);

        mEditText.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                //System.out.println("onTextChanged:arg0=" +arg0+ " start:" + arg1 + "before:" + arg2 + "count:" + arg3);
            }

            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
            }
            ///1234 5678 9012 1234
            public void afterTextChanged(Editable s) {
                ///Log.i(TAG,"afterTextChanged:s=" + s);
                mInputString = s.toString();
                if (mInputString!=null
                        &&(mInputString.length()==4
                        ||mInputString.length()==9
                        ||mInputString.length()==14)) {
                    if(!isDel){
                        mInputString += " ";
                        mEditText.setText(mInputString);
                        mEditText.setSelection(mInputString.length());
                    }
                }

                if(mInputString.length()>19) {
                    String newStr = mInputString.substring(0,19);
                    LogUtil.i(TAG,"newStr="+newStr);
                    mEditText.setText(newStr);
                    mEditText.setSelection(newStr.length());
                    Toast.makeText(WelcomeActivity.this,
                            getString(R.string.had_input_16bit),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });

        final PopupWindow pw= new PopupWindow(vPopupWindow,(int) MeasureUtil.getWidthSize(830),(int) MeasureUtil.getHeightSize(510),true);
        textViewOK.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if(event.getAction() == KeyEvent.ACTION_DOWN
                        && keyCode == KeyEvent.KEYCODE_BACK) {
                    pw.dismiss();
                    finish();
                    return true;
                }
                return false;
            }
        });

        mEditText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if(event.getAction() == KeyEvent.ACTION_DOWN) {
                    if(keyCode == KeyEvent.KEYCODE_DEL) {
                        isDel=true;
                    } else {
                        isDel = false;
                    }
                }

                if(event.getAction() == KeyEvent.ACTION_DOWN
                        && keyCode == KeyEvent.KEYCODE_BACK) {
                    pw.dismiss();
                    finish();
                    return true;
                }
                return false;
            }
        });

        textViewOK.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if(event.getAction() == KeyEvent.ACTION_DOWN
                        && keyCode == KeyEvent.KEYCODE_BACK) {
                    pw.dismiss();
                    finish();
                    return true;
                }
                return false;
            }
        });
        //OK按钮及其处理事件
        textViewOK.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //设置文本框内容
                mInputString = mEditText.getText().toString();
                if(mInputString!=null
                        &&mInputString.length()>0) {
                    if(mInputString.length()!=19&&mInputString.length()!=10) {
                        Toast.makeText(WelcomeActivity.this,
                                getResources().getString(R.string.input_16bit_code),
                                Toast.LENGTH_SHORT).show();
                        //pw.dismiss();//关闭
                        //mHandler.postDelayed(mRunnable, 500);
                        return;
                    }
                    final ConfirmDialog confirmDialog = new ConfirmDialog(WelcomeActivity.this,R.style.dialog,mInputString.trim());
                    confirmDialog.setPositiveButtonListener(new ConfirmDialog.DialogButtonListener() {
                        @Override
                        public void onClick(Dialog dlg, View v) {
                            CODE = mInputString.trim().replaceAll(" ", "");
                            LogUtil.i(TAG,"textViewOK onClick CODE="+CODE);
                            showBufferLoad();
                            activateAuth(aaa,mActivateAuthResultListener,WelcomeActivity.this.CODE);
                            confirmDialog.dismiss();
                            pw.dismiss();//关闭
                        }
                    });
                    confirmDialog.setNegativeButtonListener(new ConfirmDialog.DialogButtonListener() {
                        @Override
                        public void onClick(Dialog dlg, View v) {
                            confirmDialog.dismiss();
                            mInputString = "";
                            CODE = mInputString;
                            mEditText.setText(mInputString);
                            mEditText.setSelection(mInputString.length());
                            confirmDialog.dismiss();
                        }
                    });
                    confirmDialog.show();
                } else {
                    Toast.makeText(WelcomeActivity.this,
                            getResources().getString(R.string.input_code),
                            Toast.LENGTH_SHORT).show();
                    mEditText.setText("");
                }
            }
        });

        //Cancel按钮及其处理事件
        textViewCancel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                pw.dismiss();//关闭
                finish();
            }
        });
        //显示popupWindow对话框
        pw.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        contentView = LayoutInflater.from(this).inflate(R.layout.activity_welcome, null);
        setContentView(contentView);
        initView();
		registerNetworkReceiver();
       /// startHomeActivity();
    }

    public void onResume() {
        super.onResume();
    }
    @Override
    protected void onPause() {
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(aaaRegisterTask !=null && aaaRegisterTask.getStatus() == AsyncTask.Status.RUNNING){
            aaaRegisterTask.cancel(true);
            aaaRegisterTask=null;
        }
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(aaaActivateTask !=null && aaaActivateTask.getStatus() == AsyncTask.Status.RUNNING){
            aaaActivateTask.cancel(true);
            aaaActivateTask=null;
        }
        super.onPause();
    }
    protected void initView() {
        mLoadingLayout =  (LinearLayout)findViewById(R.id.LoadingLayout);
        TextView tv_version =(TextView)findViewById (R.id.tv_version);
        String packageName = getPackageName();
        try {
            if (!TextUtils.isEmpty(packageName)) {
                String versionName = getPackageManager().getPackageInfo(
                        packageName, PackageManager.GET_ACTIVITIES).versionName;
                if (versionName != null) {
                    tv_version.setText("V:"+versionName);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new Thread(mRunnable).start();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.currentThread().sleep(3000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                setResult(1);
//                finish();
//            }
//        }).start();
    }

    AAAActivateTask.OnResultListener mActivateAuthResulFirsttListener = new AAAActivateTask.OnResultListener() {
        @Override
        public void onResult(AAAActivateResult result) {
            hideBufferLoad();
            if(result==null) {
                return ;
            }
            LogUtil.d(TAG,"code="+result.CODE+" info="+result.INFO);
            if((Integer.valueOf(result.CODE)!=0
                    ||result.CODE.length()==0)
                    ||(result.USERID==null
                    ||result.USERID.length()==0)) {///出错，显示错误信息
                LogUtil.d(TAG,"no active,need to activate");
                mCountFail = 0;
                showPopupWindow(WelcomeActivity.this,contentView);
            } else {////success
                Toast.makeText(WelcomeActivity.this,
                        getString(R.string.activate_login),
                        Toast.LENGTH_SHORT).show();
                mCountFail=0;
                String encryptAuthString = VKNetBossUtils.encrypt(result.USERID , Constant.KEY);
                NewDTVApp.getApp().sharedPre.edit().putString("uid", encryptAuthString).commit();
                encryptAuthString = VKNetBossUtils.encrypt(result.ACTIVATETM, Constant.KEY);
                NewDTVApp.getApp().sharedPre.edit().putString("atime", encryptAuthString).commit();
                mUidString = result.USERID;
                registerAAA(aaa,mRegisterResultListener,result.USERID);
            }

        }
    };
    AAAActivateTask.OnResultListener mActivateAuthResultListener = new AAAActivateTask.OnResultListener() {
        @Override
        public void onResult(AAAActivateResult result) {
            hideBufferLoad();
            if(result==null) {
                return ;
            }
            LogUtil.d(TAG,"code="+result.CODE+" info="+result.INFO);
            if((Integer.valueOf(result.CODE)!=0
                    ||result.CODE.length()==0)
                    ||(result.USERID==null
                    ||result.USERID.length()==0)) {///出错，显示错误信息
                mCountFail++;
                if(mCountFail<FAIL_TRY_COUNT) {
                    LogUtil.i(TAG,"activate fail.try again mCountFail="+mCountFail+" code="+WelcomeActivity.this.CODE);
                    activateAuth(aaa,mActivateAuthResultListener,CODE);
                } else {
                    if((aaa = get3AIP())!=null) {
                        mCountFail = 0;
                        activateAuth(aaa,mActivateAuthResultListener,CODE);
                    } else {
                        Toast.makeText(WelcomeActivity.this,
                                getString(R.string.activate_fail) + " " + result.INFO,
                                Toast.LENGTH_SHORT).show();
                        hideBufferLoad();
                        Utils.toastDialog(WelcomeActivity.this, getString(R.string.str_data_loading_error));
                        Utils.getToastDialog().show();
                    }
                }
            } else {////success
                Toast.makeText(WelcomeActivity.this,
                        getString(R.string.activate_login),
                        Toast.LENGTH_SHORT).show();
                mCountFail=0;
                String encryptAuthString = VKNetBossUtils.encrypt(result.USERID , Constant.KEY);
                NewDTVApp.getApp().sharedPre.edit().putString("uid", encryptAuthString).commit();
                encryptAuthString = VKNetBossUtils.encrypt(result.ACTIVATETM, Constant.KEY);
                NewDTVApp.getApp().sharedPre.edit().putString("atime", encryptAuthString).commit();
                mUidString = result.USERID;
                registerAAA(aaa,mRegisterResultListener,result.USERID);
            }

        }
    };

    AAARegisterTask.OnResultListener mRegisterResultListener = new AAARegisterTask.OnResultListener() {
        @Override
        public void onResult(AAARegisterResult result) {
            hideBufferLoad();
            if(result==null) {
                return ;
            }
            LogUtil.d(TAG,"code="+result.CODE+" info="+result.INFO);
            if(Integer.valueOf(result.CODE)!=0||result.CODE.length()==0) {///出错，显示错误信息
                mCountFail++;
                if(mCountFail<FAIL_TRY_COUNT) {
                    LogUtil.i(TAG,"register fail.try again mCountFail="+mCountFail+" uid="+mUidString);
                    registerAAA(aaa,mRegisterResultListener,mUidString);
                } else {
                    if((aaa = get3AIP())!=null) {
                        mCountFail = 0;
                        registerAAA(aaa,mRegisterResultListener,mUidString);
                    } else {
                        Toast.makeText(WelcomeActivity.this,
                                getString(R.string.register_fail) + " " + result.INFO,
                                Toast.LENGTH_SHORT).show();
                        hideBufferLoad();
                        Utils.toastDialog(WelcomeActivity.this, getString(R.string.str_data_loading_error));
                        Utils.getToastDialog().show();
                        if (Integer.valueOf(result.CODE) == 20100
                                || Integer.valueOf(result.CODE) == 20001) {
                            NewDTVApp.getApp().editor.putString("uid", "").commit();
                            //mHandler.postDelayed(mRunnable, 500);
                        }
                    }
                    //showPopupWindow(WelcomeActivity.this, contentView);
                    ///finish();
                }
            } else {////success
                Toast.makeText(WelcomeActivity.this,
                        getString(R.string.register_success),
                        Toast.LENGTH_SHORT).show();
                hideBufferLoad();
//                Intent it = new Intent(WelcomeActivity.this,.class);
//                startActivity(it);
//                finish();
                setResult(1);
                finish();
            }

        }
    };
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
    }

    protected void onDestroy() {
        Dialog dialog = Utils.getToastDialog();
        if(dialog!=null&&dialog.isShowing()) {
            dialog.dismiss();
        }
        setResult(0);
        unRegisterNetworkReceiver();
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @SuppressWarnings("static-access")
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
                    ConnectivityManager connectMgr = (ConnectivityManager) getApplicationContext().getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isAvailable()) {
						/*
						 * network is ok.
						 */
                        LogUtil.d(TAG, "NET UP  network is ok.");
                        if (mDlg != null && mDlg.isShowing()) {
                            mDlg.dismiss();
                        }

                    } else {


                        LogUtil.e(TAG, "NET DOWN");
                        if (mDlg == null) {
                            LogUtil.e(TAG, "mDlg == null NET DOWN");
                            mDlg = new NetworkDialog(WelcomeActivity.this,
                                    R.style.dialog);
                            mDlg.setNegativeButtonListener(networkExitBotton);
                            mDlg.setPositiveButtonListener(networkSettingBotton);
                            mDlg.show();
                        } else {
                            LogUtil.e(TAG, "mDlg != null NET DOWN");
                            mDlg.show();
                        }

                    }

                }
            } catch (Exception e) {
                LogUtil.e(TAG, "error");
            }
        }
    };


    private void registerNetworkReceiver() {
        IntentFilter filter = new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION);
        this.registerReceiver(receiver, filter);
    }

    private void unRegisterNetworkReceiver() {
        this.unregisterReceiver(receiver);
        receiver = null;
    }

    private NetworkDialog.DialogButtonListener networkExitBotton = new NetworkDialog.DialogButtonListener() {

        @Override
        public void onClick(Dialog dlg, View v) {
            // TODO Auto-generated method stub
            if (mDlg != null) {
                mDlg.dismiss();
                finish();
            }
        }
    };

    private NetworkDialog.DialogButtonListener networkSettingBotton = new NetworkDialog.DialogButtonListener() {

        @Override
        public void onClick(Dialog dlg, View v) {
            // TODO Auto-generated method stub
            Intent resolveIntent = new Intent();
            resolveIntent.setClassName("com.android.settings",
                    "com.android.settings.Settings");
            startActivity(resolveIntent);

            if (mDlg != null) {
                mDlg.dismiss();
                mDlg=null;
                if (mLoadingLayout != null) {
                    mLoadingLayout.setVisibility(View.VISIBLE);
                }
            }
        }
    };

}
